package com.lzh.hosp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzh.hosp.model.ResponseResult;
import com.lzh.hosp.model.SysMenu;
import com.lzh.hosp.model.SysRoleMenu;
import com.lzh.hosp.model.SysUser;
import com.lzh.hosp.model.dto.SysMenuDto;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sys/menu")
@Tag(name = "菜单管理")
public class SysMenuController extends BaseController {

	/**
	 * 用户当前用户的菜单和权限信息
	 * @param principal
	 * @return
	 */
	@GetMapping("/nav")
	public ResponseResult nav(Principal principal) {
		SysUser sysUser = sysUserService.getById(principal.getName());

		// 获取权限信息
		String authorityInfo = sysUserService.getUserAuthorityInfo(sysUser.getId());// ROLE_admin,ROLE_normal,sys:user:list,....
		String[] authorityInfoArray = StringUtils.tokenizeToStringArray(authorityInfo, ",");

		// 获取导航栏信息
		List<SysMenuDto> navs = sysMenuService.getCurrentUserNav();

		Map<String,Object> params = new HashMap<>();
		params.put("authoritys",authorityInfoArray);
		params.put("nav",navs);

		return ResponseResult.ok(params);
	}

	@GetMapping("/info/{id}")
	@PreAuthorize("hasAuthority('sys:menu:list')")
	public ResponseResult info(@PathVariable(name = "id") Long id) {
		return ResponseResult.ok(sysMenuService.getById(id));
	}

	@GetMapping("/list")
	@PreAuthorize("hasAuthority('sys:menu:list')")
	public ResponseResult list() {

		List<SysMenu> menus = sysMenuService.tree();
		return ResponseResult.ok(menus);
	}

	@PostMapping("/save")
	@Operation(summary = "保存菜单")
	@PreAuthorize("hasAuthority('sys:menu:save')")
	public ResponseResult save(@Validated @RequestBody SysMenu sysMenu) {

		sysMenu.setCreated(LocalDateTime.now());

		sysMenuService.save(sysMenu);
		return ResponseResult.ok(sysMenu);
	}

	@PostMapping("/update")
	@Operation(summary = "更新菜单")
	@PreAuthorize("hasAuthority('sys:menu:update')")
	public ResponseResult update(@Validated @RequestBody SysMenu sysMenu) {

		sysMenu.setUpdated(LocalDateTime.now());

		sysMenuService.updateById(sysMenu);

		// 清除所有与该菜单相关的权限缓存
		sysUserService.clearUserAuthorityInfoByMenuId(sysMenu.getId());
		return ResponseResult.ok(sysMenu);
	}

	@PostMapping("/delete/{id}")
	@Operation(summary = "删除菜单")
	@PreAuthorize("hasAuthority('sys:menu:delete')")
	public ResponseResult delete(@PathVariable("id") Long id) {

		int count = sysMenuService.count(new QueryWrapper<SysMenu>().eq("parent_id", id));
		if (count > 0) {
			return ResponseResult.fail("请先删除子菜单");
		}

		// 清除所有与该菜单相关的权限缓存
		sysUserService.clearUserAuthorityInfoByMenuId(id);

		sysMenuService.removeById(id);

		// 同步删除中间关联表
		sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("menu_id", id));
		return ResponseResult.ok();
	}
}